//
//  LHImagePickerManager.m
//  LHImagePicker
//
//  Created by 刘辉 lewis on 2018/6/13.
//  Copyright © 2018年 刘辉 lewis. All rights reserved.
//

#import "LHImagePickerManager.h"

@implementation LHImagePickerManager
+(NSMutableArray<PHAsset*>*)lh_getAssetInPhotoAblumWithAscending:(BOOL)ascending andSortDescriptorKey:(NSString*)sortKey andMediaType:(PHAssetMediaType)type{
    NSMutableArray*assetArray=[NSMutableArray array];
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:sortKey ascending:ascending]];
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:type options:option];
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[PHAsset class]]) {
            [assetArray addObject:obj];
        }
    }];
    PHCachingImageManager *cachingImage = [[PHCachingImageManager alloc] init];
    [cachingImage startCachingImagesForAssets:assetArray targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:nil];
    return assetArray;
}
/**
 根据PHAssetMediaType计算总个数
 
 @param type PHAssetMediaType
 @return     类型总数
 */
+(NSUInteger)lh_getAssetCountWithmediaType:(PHAssetMediaType)type{
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:type options:nil];
    return result.count;
}

+(void)lh_savePhotoAlbum:(UIImage*)image andCompletion:(void(^)(BOOL success,NSError*error))completion{
    if (image) {
        //        NSMutableArray *imageIds = [NSMutableArray array];
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            //            [imageIds addObject:req.placeholderForCreatedAsset.localIdentifier];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            /** 保存相册后得到图片的PHAsset对象在这里进行后续操作*/
            if (completion) {
                completion(success,error);
            }
        }];
    }
}
@end
